package cn.jolyoulu.common.web.security.interceptors;

import cn.jolyoulu.common.web.security.constant.SecurityConstants;
import cn.jolyoulu.common.web.security.context.SecurityContextHolder;
import cn.jolyoulu.common.web.security.entity.LoginUser;
import cn.jolyoulu.common.web.security.service.TokenService;
import cn.jolyoulu.common.web.security.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @Author LuZhouJin
 * @Date 2023/3/15
 * token拦截器：认证token，加载权限数据
 */
@Slf4j
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = SecurityUtils.getToken(request);
        log.info("token ==> "+token);

        if (StringUtils.isBlank(token)){
            return true;
        }

        //本地缓存中获取出用户信息
        LoginUser<?> loginUser = tokenService.getLoginUser(token);
        if (Objects.nonNull(loginUser)){
            //将用户信息添加到全局上下文
            SecurityContextHolder.set(SecurityConstants.LOGIN_USER,loginUser);
        }else {
            log.warn("未获取到用户信息 ==> "+request.getRequestURL().toString());
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除ThreadLocal中的信息
        SecurityContextHolder.remove();
    }
}
